﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using UnityEngine;
using PegasusLettuce;
using HarmonyLib;
using System.IO;
using Hearthstone.Progression;
using PegasusShared;
using Hearthstone.DataModels;
using System.Threading;


namespace hearthstone_bepInEx
{
    [BepInPlugin("plugin.hearthstone", "hearthstone plugin", "1.0")]
    public class Main : BaseUnityPlugin
    {
        // 插件所在文件夹
        // string location = System.Reflection.Assembly.GetExecutingAssembly().Location; 

        // unityexplore 调试用的，不用管 UnityExplorer.ExplorerCore.Log("");
        public static ConfigEntry<KeyboardShortcut> runningKey { get; set; }
        public static ConfigEntry<long> teamIdConfig { get; set; }
        public static long teamId;
        public static ConfigEntry<int> bossIdConfig { get; set; }
        public static int bossId;
        public static ConfigEntry<bool> findSurpriseConfig { get; set; } // true:找神秘人模式 false: 打boss模式
        public static bool findSurprise;
        public static ConfigEntry<bool> isRunningConfig { get; set; }
        public static bool isRunning;

        public static ConfigEntry<int> maxBattleConfig { get; set; } // 最多战斗几场，超过这个数就重开
        public static int maxBattle;

        public static ConfigEntry<int> delayConfig { get; set; }
        public static int delay;
        private static Harmony _patch;

        void Start()
        {
            Logger.LogInfo("炉石插件已启动");
            // 配置 
            runningKey = Config.Bind("热键", "开关热键", new KeyboardShortcut(KeyCode.F8));
            isRunningConfig = Config.Bind("脚本配置", "是否启动", true);
            isRunning = isRunningConfig.Value;
            findSurpriseConfig = Config.Bind("脚本配置", "是否找神秘人", true, new ConfigDescription("是：优先找神秘人然后退出，否：优先通关Boss。"));
            findSurprise = findSurpriseConfig.Value;
            maxBattleConfig = Config.Bind("脚本配置", "最多战斗几关", 3, new ConfigDescription("最多战斗几关，超过这个数就重开"));
            maxBattle = maxBattleConfig.Value;

            teamIdConfig = Config.Bind("脚本配置", "队伍 ID", 0L);
            teamId = teamIdConfig.Value;

            bossIdConfig = Config.Bind("脚本配置", "Boss ID", 57);
            bossId = bossIdConfig.Value;
            // 默认延时500毫秒
            delayConfig = Config.Bind("脚本配置", "延时", 500);
            delay = delayConfig.Value;
            _patch = Harmony.CreateAndPatchAll(typeof(Main));
        }

        private void OnDestroy()
        {
            _patch?.UnpatchSelf();
            mainForm.Close();
            mainForm = null;
        }
         
         

        public static void claimMercenaryTask()
        {
            // 完成任务
            NetCache.NetCacheMercenariesVillageVisitorInfo netObject = NetCache.Get().GetNetObject<NetCache.NetCacheMercenariesVillageVisitorInfo>();
            if (netObject != null)
            {
                for (int i = 0; i < netObject.VisitorStates.Count; i++)
                {
                    if (netObject.VisitorStates[i].ActiveTaskState.Status_ == MercenariesTaskState.Status.COMPLETE)
                    {
                        Network.Get().ClaimMercenaryTask(netObject.VisitorStates[i].ActiveTaskState.TaskId);
                    }
                }
            }
        }


        [HarmonyPrefix]
        [HarmonyPatch(typeof(DialogManager), "ShowPopup", new Type[] {typeof(AlertPopup.PopupInfo), typeof(DialogManager.DialogProcessCallback), typeof(object) })]
        public static bool CloseDialog()
        {
            return !isRunning;
        }


        //[HarmonyPrefix]
        //[HarmonyPatch(typeof(AlertPopup), "Show")]
        //public static bool CloseAlert()
        //{
        //    return !isRunning; 
        //}

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Hearthstone.HearthstoneApplication), "OnApplicationFocus")]
        public static bool SetApplicationFocus(bool focus)
        {
            return false;
        }


        [HarmonyPostfix]
        [HarmonyPatch(typeof(RewardPopups), "ShowMercenariesRewards")]
        public static void AutoGetRewards(bool autoOpenChest, NetCache.ProfileNoticeMercenariesRewards rewardNotice, Action doneCallback = null)
        {
            if (!isRunning) return;
            Network.Get().AckNotice(rewardNotice.NoticeID); 
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(RewardBoxesDisplay), "RewardPackageOnComplete")]
        public static void openBox(RewardBoxesDisplay.RewardBoxData boxData)
        {
            if (!isRunning) return;
            // 自动开箱 
            boxData.m_RewardPackage.TriggerPress();

        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(RewardBoxesDisplay), "OnDoneButtonShown")]
        public static void BoxConfirm()
        {
            if (!isRunning) return;
            // 开完箱后自动点确定
            RewardBoxesDisplay.Get().m_DoneButton.TriggerPress();
            RewardBoxesDisplay.Get().m_DoneButton.TriggerRelease();
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "DisplayNewlyGrantedAnomalyCards")]
        public static void ClickNewlyCards(PegasusLettuce.LettuceMap lettuceMap, int completedNodeId)
        {
            if (!isRunning || lettuceMap == null) return;
            RandomClick(3);
        }


        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "ShouldShowVisitorSelection")]
        public static void AutoVisitor(PegasusLettuce.LettuceMap map, ref bool __result)
        {
            // 自动神秘人
            if (!isRunning || map == null) return;
            __result = false;
        }


        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMap), "CreateMapFromProto")]
        public static void onGameEnd(PegasusLettuce.LettuceMap lettuceMap)
        {
            if (!isRunning || lettuceMap == null) return;
            // 游戏结束时自动触发

            if (lettuceMap.HasPendingTreasureSelection && lettuceMap.PendingTreasureSelection.TreasureOptions.Count > 0)
            {
                int selectOption = 0;
                int current = -1;
                foreach (int dbId in lettuceMap.PendingTreasureSelection.TreasureOptions)
                {
                    ++current;
                    // 宝藏实体
                    EntityDef treasure = DefLoader.Get().GetEntityDef(dbId, false);
                    // 宝藏名称，可用于黑白名单
                    string name = treasure.GetName();
                    if (name.Contains("靴"))
                    {
                        continue;
                    }
                    selectOption = current;
                    Debug.Log("treasure: " + name);
                }
                // 选择宝藏0
                Network.Get().MakeMercenariesMapTreasureSelection(selectOption);
            }

            if (lettuceMap.HasPendingVisitorSelection && lettuceMap.PendingVisitorSelection.VisitorOptions.Count > 0)
            {
                int selectOption = 0;
                 
                // 选择神秘人0   
                Network.Get().MakeMercenariesMapVisitorSelection(selectOption);
            }
            // 打完boss去地图界面
            foreach (LettuceMapNode lettuceMapNode in lettuceMap.Nodes)
            {
                if (GameUtils.IsFinalBossNodeType((int)lettuceMapNode.NodeTypeId) && lettuceMapNode.NodeState_ == LettuceMapNode.NodeState.COMPLETE)
                {
                    SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_BOUNTY_BOARD, SceneMgr.TransitionHandlerType.NEXT_SCENE, null, null);
                    return;
                }
            } 
            // 打完一把领一次任务
            claimMercenaryTask();
        }



        public void EndTurn()
        {
            // 回合结束
            InputManager.Get().DoEndTurnButton();
        }

        public void utils()
        {
            // 草稿纸，分析顺手写的，不用管
            // RewardTrackManager.Get().TrackDataModel.XpProgress;  // 当前经验条

            List<LettuceTeam> teams = CollectionManager.Get().GetTeams();
            foreach (LettuceTeam lettuceTeam2 in teams)
            {

                Logger.LogInfo($"{lettuceTeam2.Name}, {lettuceTeam2.ID}");
            }

        }

        public void getAllBoss()
        {
            // 获取boss列表,实际到119就没了
            for (int i = 1; i < 200; i++)
            {
                LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(i);
                if (record != null)
                {
                    string heroic = record.Heroic ? "英雄" : "普通";
                    Debug.Log($"{i} {heroic } {record.BountySetRecord.Name.GetString(true)} {record.FinalBossCardRecord.Name.GetString(true)}");
                }
            }
        }

        public void ShowInfo(String info)
        {
            // 在游戏界面上显示文字
            UIStatus.Get().AddInfo(info);
        }


        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "InitializeMapDataFromProto")]
        public static void parseMap()
        {
            if (!isRunning) return;
            // 对战结束后或者重进地图，地图数据才刷新，领取惊喜、赐福等都不会刷新，所以需要我们手动计算状态
            ChooseNextMapNode();
        }


        public static void ChooseNextMapNode()
        {
            isGetingPath = true;
            // 此方法根据求出的最短路径选择。
            GetShortestPath();
            // 超出期望数就重开
            if (findSurprise && needBattle > maxBattle)
            {
                RetireMap(); 
                return;
            }
            // 如果目标还未完成
            if (shortestPath.Last().NodeState_ != LettuceMapNode.NodeState.COMPLETE)
            {
                for (int i = 0; i < shortestPath.Count; i++)
                {
                    LettuceMapNode mapNode = shortestPath[i];
                    if (mapNode.NodeState_ == LettuceMapNode.NodeState.UNLOCKED)
                    { 
                        WriteTic();
                        // 需要战斗的关卡
                        if (Array.IndexOf(needBattleIds, mapNode.NodeTypeId) > -1)
                        {
                            startBattle(mapNode.NodeId);
                            isGetingPath = false;
                            return;
                        }
                        else
                        {
                            Network.Get().ChooseLettuceMapNode(mapNode.NodeId);
                            // 领取惊喜、赐福等都不会刷新，所以需要我们手动计算状态
                            mapNode.NodeState_ = LettuceMapNode.NodeState.COMPLETE;

                            // 不是最后一个
                            if (i < shortestPath.Count - 1)
                            {
                                // 下一个解锁
                                shortestPath[i + 1].NodeState_ = LettuceMapNode.NodeState.UNLOCKED;
                            }
                            if (mapNode.NodeTypeId == 0U)
                            {
                                for (int j = i + 1; j < shortestPath.Count - 1; j++)
                                {
                                    shortestPath[j].NodeState_ = LettuceMapNode.NodeState.COMPLETE;
                                }
                            }
                            // 最后一个
                            if (i == shortestPath.Count - 1)
                            {
                                // 尝试获取神秘人
                                // 完成，直接退出
                                Network.Get().MakeMercenariesMapVisitorSelection(0);
                                RetireMap();
                                realtimeSinceStartup += 5f;

                            }
                            RandomClick(3);

                        }
                    }
                }
            }
            else
            {
                // 完成，直接退出
                RetireMap();
                realtimeSinceStartup += 5f;
            }

        }
        public static List<LettuceMapNode> shortestPath = new List<LettuceMapNode>();
        public static bool isGetingPath = false;
        public static int needBattle = 0;
        public static uint[] needBattleIds = new uint[] { 1U, 2U, 3U, 22U };
        public static uint[] surpriseIds = new uint[] { 0U, 14U, 18U, 19U, 23U, 44U };

        public static void GetShortestPath()
        {
            // 此方法用于分析地图节点，求出最短路径
            // 获取地图结点 
            NetCache.NetCacheLettuceMap netObject = NetCache.Get().GetNetObject<NetCache.NetCacheLettuceMap>();
            List<LettuceMapNode> nodesList = netObject.Map.Nodes;

            int surpriseNodeId = nodesList.Count - 1;
            int bossNodeId = surpriseNodeId;
            using (List<LettuceMapNode>.Enumerator enumerator = nodesList.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    LettuceMapNode mapNode = enumerator.Current;
                    //Debug.Log($"NodeId:{mapNode.NodeId}, NodeRole:{mapNode.NodeRole}, NodeTypeId:{mapNode.NodeTypeId}, NodeState:{mapNode.NodeState_}");
                    if (Array.IndexOf(surpriseIds, mapNode.NodeTypeId) > -1)
                        surpriseNodeId = (int)mapNode.NodeId;
                    else if (mapNode.NodeTypeId == 3)
                        bossNodeId = (int)mapNode.NodeId;

                    // NodeTypeId
                    // 0惊喜  22,1普通  2精英  3boss  20营火   26护卫,42斗士,34,43施法赐福   45复活  惊喜选项0, 14炸弹, 18, 19破坏, 23, 44
                    // 子节点
                    List<uint> childNodeIds = mapNode.ChildNodeIds;
                }
            }

            int len = nodesList.Count;


            // Dijkstra 算法
            int target = bossNodeId;

            if (findSurprise)
            {
                target = surpriseNodeId;
            }
            int[] cost = new int[100];
            cost[22] = 4;
            cost[1] = 4;
            cost[2] = 6;
            cost[3] = 7;
            cost[20] = 100;
            int[] pre = new int[100];
            int[] dis = new int[100];
            for (int i = 0; i < 100; i++) dis[i] = 0x3f3f3f3f;
            bool[] vis = new bool[100];
            dis[1] = 0;
            for (int i = 1; i < len; i++)
            {
                int u = 0, mind = 0x3f3f3f3f;
                for (int j = 1; j < len; j++)
                {
                    if (!vis[j] && dis[j] < mind)
                    {
                        u = j;
                        mind = dis[j];
                        vis[u] = true;
                    }
                    foreach (uint mapNodeId in nodesList[u].ChildNodeIds)
                    {
                        int v = (int)mapNodeId;
                        LettuceMapNode mapNode = nodesList[v];
                        int w = cost[mapNode.NodeTypeId];
                        if (dis[v] > dis[u] + w)
                        {
                            dis[v] = dis[u] + w;
                            pre[v] = u;
                        }
                    }
                }
            }



            needBattle = 0;
            List<LettuceMapNode> result = new List<LettuceMapNode>();
            while (target != 0)
            {
                LettuceMapNode mapNode = nodesList[target];
                if (Array.IndexOf(needBattleIds, mapNode.NodeTypeId) > -1)
                {
                    // 统计需要战斗的场数
                    ++needBattle;
                }
                result.Add(mapNode);
                target = pre[target];
            }
            result.Reverse();
            shortestPath = result;
            string resultStr = "";
            foreach (LettuceMapNode mapNode in result)
            {
                resultStr += mapNode.NodeId + ", ";
            }
            Debug.Log(resultStr);
        }



         
        public static void RetireMap()
        {
            // 放弃
            Network.Get().RetireLettuceMap();
            realtimeSinceStartup += 5f;
            RandomClick(5);

            Debug.Log("Retire Map");
        }

        public static void startBattle(uint mapNodeId)
        {
            // 进入战斗界面，需要提供NodeId
            GameMgr.Get().FindGame(GameType.GT_MERCENARIES_PVE, FormatType.FT_WILD, 3790, 0, 0L, null, null, false, null, (int?)mapNodeId, 0L, GameType.GT_UNKNOWN);
        }

        // 战斗相关
        public static void Battle()
        {
            // 选择技能或者上人阶段
            if (GameState.Get().GetResponseMode() == GameState.ResponseMode.OPTION)
            {
                ZonePlay myZonePlay = ZoneMgr.Get().FindZoneOfType<ZonePlay>(Player.Side.FRIENDLY);
                // 人还没上完
                // 获取回合结束按钮上的文字
                if (EndTurnButton.Get().m_MyTurnText.Text.IndexOf("/") > -1)
                {
                    // 手牌
                    ZoneHand zoneHand = ZoneMgr.Get().FindZoneOfType<ZoneHand>(Player.Side.FRIENDLY);
                    if (zoneHand != null)
                    {
                        int selectedOption = 1; // 卡牌位置，1开始
                        for (int i = 1; i <= zoneHand.GetCardCount(); i++)
                        {
                            // 上人
                            GameState gameState = GameState.Get();
                            gameState.SetSelectedOption(selectedOption);
                            gameState.SetSelectedSubOption(-1);
                            gameState.SetSelectedOptionTarget(0);
                            gameState.SetSelectedOptionPosition(myZonePlay.GetCardCount() + 1); // 上场位置，1开始
                            gameState.SendOption();
                            WriteTic();
                            return;
                        }
                    }
                }

                // 如果没有选择技能的框框
                Entity entity = ZoneMgr.Get().GetLettuceAbilitiesSourceEntity();
                if (entity == null)
                {
                    // 遍历场上的佣兵
                    using (List<global::Card>.Enumerator enumerator3 = myZonePlay.GetCards().GetEnumerator())
                    {
                        while (enumerator3.MoveNext())
                        {
                            Card card3 = enumerator3.Current;
                            entity = card3.GetEntity();
                            // 如果该佣兵没有选择技能
                            if (!entity.HasSelectedLettuceAbility() || !entity.HasTag(GAME_TAG.LETTUCE_HAS_MANUALLY_SELECTED_ABILITY))
                            {
                                // 就让他出现选择技能的框框
                                ZoneMgr.Get().DisplayLettuceAbilitiesForEntity(entity);
                                WriteTic();
                                return;
                            }
                        }
                    }
                }
                else
                { 
                    Debug.Log(entity.GetName());
                    string heroName = entity.GetName();
                    MercenariesAbilityTray abilityTray = ZoneMgr.Get().GetLettuceZoneController().GetAbilityTray();
                    // 获得选择技能中的佣兵的技能
                    List<Card> list = (List<Card>)Traverse.Create(abilityTray).Field("m_abilityCards").GetValue();
                    // 第0个技能
                    Entity spell = list[0].GetEntity();
                    Debug.Log($"{spell.GetName()} damage: {spell.GetDamageBonus()}");
                    if (heroName.Contains("迦顿") || heroName.Contains("拉格纳"))
                    {
                        spell = list[1].GetEntity();
                    }
                    // 点击第0个技能
                    Traverse.Create(InputManager.Get()).Method("HandleClickOnCardInBattlefield", new object[] { spell, true }).GetValue();

                    // 如果是抉择技能，就会到这
                    if (GameState.Get().GetResponseMode() == GameState.ResponseMode.SUB_OPTION)
                    { 
                        // 抉择的选项列表
                        List<Card> friendlyCards = ChoiceCardMgr.Get().GetFriendlyCards();
                        // 这里施放的是最后一个抉择选项，可自定义
                        InputManager.Get().HandleClickOnSubOption(friendlyCards[friendlyCards.Count - 1].GetEntity(), false);
                    }
                }
                WriteTic();
                return;
            }
            // 选择完了技能，但还要选择技能目标就会到这里
            if (GameState.Get().GetResponseMode() == GameState.ResponseMode.OPTION_TARGET)
            {
                // 敌方战场
                ZonePlay zonePlay = ZoneMgr.Get().FindZoneOfType<ZonePlay>(Player.Side.OPPOSING);
                // 这里默认的是第一个合法目标...可自定义
                foreach (Card card in zonePlay.GetCards())
                {
                    // 合法目标
                    if (card.GetActor().GetActorStateType() == ActorStateType.CARD_VALID_TARGET || card.GetActor().GetActorStateType() == ActorStateType.CARD_VALID_TARGET_MOUSE_OVER)
                    {
                        Traverse.Create(InputManager.Get()).Method("HandleClickOnChoice", new object[] { card.GetEntity() }).GetValue();
                        WriteTic();
                        return;
                    }
                }
                // 不能选敌方就选我方战场
                ZonePlay zonePlay2 = ZoneMgr.Get().FindZoneOfType<ZonePlay>(Player.Side.FRIENDLY);
                foreach (Card card2 in zonePlay2.GetCards())
                {
                    if (card2.GetActor().GetActorStateType() == ActorStateType.CARD_VALID_TARGET || card2.GetActor().GetActorStateType() == ActorStateType.CARD_VALID_TARGET_MOUSE_OVER)
                    {
                        Traverse.Create(InputManager.Get()).Method("HandleClickOnChoice", new object[] { card2.GetEntity() }).GetValue();
                        WriteTic();
                        return;
                    }
                }
            }

        }

        public static void RandomClick(int cnt = 1,float posX =-1, float posY=-1  )
        {
            // 随机点击cnt次
            // 随机种子
            UnityEngine.Random.InitState((int)DateTime.Now.Ticks);
            // 取屏幕中间坐标点
            if (posX < 0)
                posX = (float)(Screen.width / 2.0);
            if (posY < 0)
                posY = (float)(Screen.height / 2.5);
            // 左右浮动
            float xOffset = (float)(Screen.width * 0.01);
            float yOffset = (float)(Screen.height * 0.01);
            while (cnt-- > 0 && clickQueue.Count <= 20)
            {
                posX = (float)Math.Round((double)(posX + UnityEngine.Random.Range(0f - xOffset, xOffset)), MidpointRounding.AwayFromZero);
                posY = (float)Math.Round((double)(posY + UnityEngine.Random.Range(0f - yOffset, yOffset)), MidpointRounding.AwayFromZero);
                
                clickQueue.Enqueue(new float[] { posX, posY });  
            }
        }
        public static void StartClickThread()
        {
            Thread thread = new Thread(new ThreadStart(Click));
            thread.Start();
            float[] clickPos = clickQueue.Dequeue();
            mousePosX = clickPos[0];
            mousePosY = clickPos[1];
            Debug.Log($"click {mousePosX}, {mousePosY}");
            mouse5 = true;
        }

        public static float mousePosX = 5;
        public static float mousePosY = 5;
        public static bool mouse2 = false;
        public static bool mouse3 = false;
        public static bool mouse4 = false;
        public static bool mouse5 = false;
        public static int mouseCnt = 0;

        public static Queue<float[]> clickQueue = new Queue<float[]>();

        [HarmonyPostfix]
        [HarmonyPatch(typeof(InputCollection), "GetMousePosition")]
        public static void MousePos(ref Vector3 __result)
        {
            if (mouse5)
            {
                __result = new Vector3(mousePosX, mousePosY, 0f);
            }
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(InputCollection), "GetMouseButton")]
        public static void MouseButton(ref bool __result, int button)
        {
            if (mouse2 && button == 0)
            {
                __result = true;
            }
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(InputCollection), "GetMouseButtonDown")]
        public static void MouseButtonDown(ref bool __result, int button)
        {
            if (mouse3 && button == 0)
            {
                ++mouseCnt;
                if (mouseCnt == 2)
                {
                    mouseCnt = 0;
                    mouse3 = false;
                    mouse2 = true;
                }

                __result = true;
            }
        }
        [HarmonyPostfix]
        [HarmonyPatch(typeof(InputCollection), "GetMouseButtonUp")]
        public static void MouseButtonUp(ref bool __result, int button)
        {
            if (mouse4 && button == 0)
            {
                mouse4 = false;
                __result = true;
            }
        }

        public static void Click()
        {
            Thread.Sleep(15);
            mouse3 = true;
            Thread.Sleep(70);
            mouse2 = false;
            mouse4 = true;
            Thread.Sleep(15);
            mouse5 = false;
        }

        private static float lastRunningTime = 0;
        private static float realtimeSinceStartup = 0;
        private static float clickDelay = 0;

        public static void WriteTic()
        {
            lastRunningTime = 0;
            //Debug.Log("WriteTic");
        }

        void Update()
        {
            // 热键开关脚本
              
            if (runningKey.Value.IsDown())
            {
                isRunning = !isRunning;
                isRunningConfig.Value = isRunning;
                this.mainForm.runningButton.Text =  isRunning ? "结束" : "运行";
                ShowInfo("脚本已" + (isRunning ? "开启" : "关闭"));
            }
            // 如果没打开就不用继续执行了
            if (!isRunning)
                return;
            lastRunningTime += Time.deltaTime;

            if (lastRunningTime > 200f && isRunning)
            {
                // 200秒不动就退出
                Application.Quit();
            }

            clickDelay -= Time.deltaTime;
            if (clickDelay < 0f && clickQueue.Count > 0)
            {
                StartClickThread();
                clickDelay = 2.5f;
                return;
            }

            if (Time.realtimeSinceStartup - realtimeSinceStartup <= 1.5f)
            {
                return;
            } 
            realtimeSinceStartup = Time.realtimeSinceStartup;
             
             

            GameMgr gameMgr = GameMgr.Get();
            GameType gameType = gameMgr.GetGameType();
            SceneMgr sceneMgr = SceneMgr.Get();
            SceneMgr.Mode mode = sceneMgr.GetMode();
            GameState gameState = GameState.Get();
            //Debug.Log($"Mode: {mode}");

            if (gameMgr.IsFindingGame())
            {
                realtimeSinceStartup += 2f;
            }
            else if (gameType == GameType.GT_UNKNOWN && gameState == null)
            {
                switch (mode)
                {
                    case SceneMgr.Mode.HUB: // 选择模式界面
                        // 去村庄
                        sceneMgr.SetNextMode(SceneMgr.Mode.LETTUCE_VILLAGE, SceneMgr.TransitionHandlerType.SCENEMGR, null, null);
                        realtimeSinceStartup += 6f;
                        WriteTic();
                        return;

                    case SceneMgr.Mode.LETTUCE_VILLAGE:  //  村庄
                        // 去战斗地图界面, 如果没进地图会自动跳到选boss界面
                        SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_MAP, SceneMgr.TransitionHandlerType.NEXT_SCENE, null, null);
                        realtimeSinceStartup += 4f;
                        WriteTic();
                        return;
                    case SceneMgr.Mode.LETTUCE_BOUNTY_BOARD: // 选择boss界面
                        LettuceVillageDisplay.LettuceSceneTransitionPayload lettucePayload = new LettuceVillageDisplay.LettuceSceneTransitionPayload();
                        LettuceBountyDbfRecord record = GameDbf.LettuceBounty.GetRecord(92);
                        lettucePayload.m_SelectedBounty = record;
                        lettucePayload.m_SelectedBountySet = record.BountySetRecord;
                        lettucePayload.m_IsHeroic = record.Heroic;
                        SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_BOUNTY_TEAM_SELECT, SceneMgr.TransitionHandlerType.CURRENT_SCENE, null, lettucePayload);
                        WriteTic();
                        realtimeSinceStartup += 4f;
                        return;
                    case SceneMgr.Mode.LETTUCE_BOUNTY_TEAM_SELECT: // 选择队伍界面
                        // TODO 暂时后面根据配置改  
                        
                        if (teamId == 0 || bossId == 0)
                        {
                            ShowInfo("未设置佣兵队伍"); 
                            isRunning = false;
                            return;
                        }
                        LettuceVillageDisplay.LettuceSceneTransitionPayload lettucePayload2 = new LettuceVillageDisplay.LettuceSceneTransitionPayload();
                        LettuceBountyDbfRecord record2 = GameDbf.LettuceBounty.GetRecord(bossId);
                        lettucePayload2.m_TeamId = teamId;
                        lettucePayload2.m_SelectedBounty = record2;
                        lettucePayload2.m_SelectedBountySet = record2.BountySetRecord;
                        lettucePayload2.m_IsHeroic = record2.Heroic;
                        SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_MAP, SceneMgr.TransitionHandlerType.CURRENT_SCENE, null, lettucePayload2);
                        WriteTic();
                        realtimeSinceStartup += 6f;
                        return;
                    case SceneMgr.Mode.LETTUCE_MAP: // 战斗地图
                        Debug.Log($"tic:{lastRunningTime}");
                        if (lastRunningTime > 20f)
                        {
                            // 如果一直不动，先回村庄再重新进
                            sceneMgr.SetNextMode(SceneMgr.Mode.LETTUCE_VILLAGE, SceneMgr.TransitionHandlerType.SCENEMGR, null, null);
                            realtimeSinceStartup += 6f;
                            WriteTic();
                        }
                        return;
                    default:
                        RandomClick();
                        return;

                }
            }
            else if (gameType == GameType.GT_MERCENARIES_PVE && mode == SceneMgr.Mode.GAMEPLAY && gameState.IsGameCreatedOrCreating())
            {
                // 如果已经在战斗界面了
                // 游戏还没结束
                if (!gameState.IsGameOver())
                {
                    // 没有其他操作了，点击回合结束
                    if (EndTurnButton.Get().m_ActorStateMgr.GetActiveStateType() == ActorStateType.ENDTURN_NO_MORE_PLAYS)
                    {
                        EndTurn();
                    }
                    else
                    {
                        // 否则就战斗
                        realtimeSinceStartup += 1f;
                        Battle();
                    }
                }
                // 出现结束界面
                else if (EndGameScreen.Get())
                {
                    PegUIElement hitbox = EndGameScreen.Get().m_hitbox;
                    if (hitbox != null)
                    {
                        hitbox.TriggerPress();
                        hitbox.TriggerRelease();
                        // 随机点点
                        RandomClick(3);
                        realtimeSinceStartup += 5f;
                    }
                }
            } else
            {
                realtimeSinceStartup += 3f;
                RandomClick();
            }
        }

        private void OnGUI()
        {
            if (GUI.Button(new Rect(1f, 1f, Screen.width / 25, Screen.width / 40), new GUIContent("设置")))
            {
                if (mainForm == null)
                {
                    mainForm = new MainForm();
                    mainForm.Show();
                }
                else if (mainForm.IsDisposed)
                {
                    mainForm = new MainForm();
                    mainForm.Show();
                }
                else
                {
                    mainForm.Activate();
                }
            }

        }

        MainForm mainForm;

    }

}
